# coding=utf-8
import random
import requests
from app_admin.extensions.redis import redis


class Sms:
    def __init__(self):
        self.app = None
        self.api_url = 'http://v.juhe.cn/sms/send'
        self.redis = redis

    def init_app(self, app):
        self.app = app

    @classmethod
    def generate_code(cls):
        return random.randint(1000, 9999)

    def send(self, phone):
        code = self.generate_code()
        params = {
            'key': self.app.config.get('SMS_APPKEY'),
            'mobile': phone,
            'tpl_id': self.app.config.get('SMS_TPL_ID'),
            'tpl_value': '#code#=%s' % code,
        }
        response = requests.get(self.api_url, params=params)
        result = response.json()
        self.save_to_redis(phone, code)
        if result:
            error_code = result['error_code']
            if error_code:
                return False
            else:
                return True

    def save_to_redis(self, phone, code):
        self.redis.set('SMS_CODE_%s' % phone, code)
        self.redis.expire('SMS_CODE_%s' % phone, 60 * 30)


sms = Sms()
